
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import {Switch } from 'antd-mobile';
import * as Actions from '../../actions'
import Header from '../../components/Header'
import utils from '../../utils'
import MeScrollContainer from '../../components/MeScroll'
import Numbers from '../../components/Numbers'

export class GoodsItem extends React.PureComponent{
  onClickLeft(){
    if(this.props.onClickLeft instanceof Function){
     this.props.onClickLeft
   }
  } 
  
  render(){
    let { item } =this.props
    return <section className='order-product-item' >
          <div className='item' >
            <div className='item-center' onClick={ this.onClickLeft.bind(this,item.goods_id)}>
                <img className='image' src={item.goods_image || item.goods_img}/>
            </div>
            <div className='item-right'>
                  <div className='line-clamp-2 name'>{item.goods_name}</div> 
                  {
                      item.spec_str ? <div className="spec">
                          {item.spec_str}</div> : ""
                  }
                 
                  <div className="money-footer">
                      <span className="money red">${item.goods_price}</span>
                      <div className="step-right">
                      <Numbers minNum={0} value={+item.goods_num} onCallBack={(num)=>{
                                this.props.changeGoodsNum(num)
                               }} />
                          
                      </div>
                  </div>
            </div>
          </div> 
          <div className='gift-list'>
          {
            item.gift_goods.goods_id?<SubGoodsItem onClickLeft_gift={this.props.onClickLeft_gift}  type={1} gitem={item.gift_goods}/>:null
          }
          {
            item.exchange_goods.goods_id?<SubGoodsItem changeGiftGoodsNum={this.props.changeGiftGoodsNum} onClickLeft_gift={this.props.onClickLeft_gift} type={2}  gitem={item.exchange_goods}/>:null
          }
          </div>
      </section>
  }
}

export class SubGoodsItem extends React.PureComponent{
  onClickLeft_gift(){
    if(this.props.onClickLeft_gift instanceof Function){
     this.props.onClickLeft_gift
   }
  } 
  changeGiftGoodsNum(){
    if(this.props.onClickLeft_gift instanceof Function){
     this.props.changeGiftGoodsNum
   }
  }
  render(){
    let { gitem,type } =this.props
    return (
       <div className='gitem'>
          <img className='limg' 
            onClick={ this.onClickLeft_gift.bind(this,gitem.goods_id,type)} 
            src={gitem.goods_image} style={{width:'60px',height:'60px'}}
          />
          <div className='rinfo'>
            <p className='line-clamp-2 name'>{gitem.goods_name}</p>
            <p className='line-clamp-1 spec'>{gitem.spec_str}</p>
            {
              type ==2?<p className='red'>${gitem.goods_price}</p>:<p className='red'>free gift</p>
            }
            {
              type == 2?
             <div className='num-btn-plane'> <Numbers minNum={0} value={+gitem.goods_num} onCallBack={(num)=>{
                        this.props.changeGiftGoodsNum(num)
                       }} /></div>
                       :
              null
            }
            
          </div>
        </div>
      )
  }
}


class ConfirmationOrder extends Component{
  static contextTypes={
    router:PropTypes.object.isRequired,
  }
  constructor(props) {
    super(props);
    this.state={
      checked:false,
      score:-1
    }
  }
  componentDidMount(){
    let {actions} =this.props 
    actions.getTempCartbyStore()
    actions.getAddressList({},{isCache:true})
    actions.getScoreInfo({},{callback:(res)=>{
      if(res.code ==200 && res.data){
        this.setState({ ...res.data,score:res.data.total_score - res.data.frozen_score})
      }
    }})
  }
  updateTempCart(num){
    let {tempCart,actions} =this.props 
    tempCart[0].goods_num=num
    actions.addTempCart(tempCart)
  }
  onTextChange(type,e){
    this.setState({
      [type]:e.target.value
    })
  }
  //更新附属商品的数量(ps:只有兑换商品能修改数量)
  changeGiftGoodsNum =(num) =>{
    let {actions,tempCart} = this.props
    tempCart[0].exchange_goods.goods_num=num
    actions.addTempCart(tempCart)

  }
  submit(){
    let {actions,tempCart,address } = this.props
    let data={
      ...tempCart[0],
      recv_addr_id:address.addr_id,
      use_score:this.state.checked?1:0,
      note:this.state.note||'',
      gift_goods_id:JSON.stringify(tempCart[0].gift_goods),
      exchange_goods_id:JSON.stringify(tempCart[0].exchange_goods),

    }
    delete data.gift_goods 
    delete data.exchange_goods
    actions.buyNow(data,{callback:(res)=>{
      if(res.code ==200){
         //下单成功后，把商品从购物车中删除
        actions.addTempCart([])
        utils.msg({text:res.message,code:1})
        this.context.router.history.push('/order/pay')

      }
     
    }})
  }
  changeAddress(){
    this.context.router.history.push('/address/list/order')
  }
  addAddress(){
    this.context.router.history.push('/address/edit/0')
  }
  render(){
    let { tempCart,address} =this.props 
    let {checked ,score} =this.state
   
    let init={money:0,score:0}
    var sum = tempCart.reduce((initJson={money:0,score:0},next)=>{
        initJson.money = (next.goods_num * next.goods_price) + initJson.money;
        initJson.score = (next.goods_use_score * next.goods_price) + initJson.score;
        return initJson
    }, init);

    return(
      <div className='order-container '>
        <Header title={'Order confirmation'} leftBtn={true} leftBtnTouch={()=>{
          this.context.router.history.goBack()
        }}/>
        <MeScrollContainer>
          {/*地址 begin*/}
          {
            address.addr_id>0?
            <div className='address-context' onClick={this.changeAddress.bind(this)}>
              <i className='iconfont icon-dizhi'></i>
              <div className='aleft'>
                <p className="p1">addressee：<span className='txt'>{address.recv_name}  {address.recv_mobile}</span></p>
                <p className="p2" style={{'paddingTop':"8px"}}>Address of the consignee：
                  <span className='txt'>{address.recv_country}{address.recv_province||''}{address.recv_city||''}{address.recv_area||''}{address.recv_address||''}</span>
                </p>
              </div>
              <div className='aright'><i className='iconfont icon-jiantou'></i></div>
            </div>
          :
            <div className='address-context' style={{'textAlign':"center"}} onClick={this.addAddress.bind(this)}>
              <div className='aleft'>
               <i className='iconfont icon-add'></i> add address
              </div>
              <div className='aright'><i className='iconfont icon-jiantou'></i></div>
            </div>
          }
          
          {/*地址 end*/}
          
          {
            sum.score >0 && score < sum.score? 
            <div className='score-tip'>Only {score} of your points are not enough to exchange the current goods</div>
            :null
          }

          {/*商品 begin*/}
          {
            tempCart.map((item,i) =>{
              return(
                <div key={i} className='cart-container buynow-container'>
                  <GoodsItem 
                  item={item}  
                  changeGoodsNum={(num) =>{
                    this.updateTempCart(num)
                  }}
                  changeGiftGoodsNum={(num) =>{
                    this.changeGiftGoodsNum(num)
                  }}
                  onClickLeft={(id)=>{
                    this.context.router.history.push(`/goods/${id}`)
                  }}
                  onClickLeft_gift={(id,type)=>{
                    this.context.router.history.push(`/subGoods/${id}/${type}`)
                  }}
                  />
                </div>
                
                )
            })
          }
          {/*商品 end*/}

          <div className='buyer-context margin-top-10'>
            <div className='input-item'>
              <span className='s1'>Buyer's notes:</span>
              <input value={this.state.note||''}  onChange={this.onTextChange.bind(this,'note')} type="text" className='s2' />
            </div>
          </div>
          {
            sum.score >0 && score>= sum.score?
            <div className='buyer-context margin-top-10'>
              <div className='input-item between'>

                <span className='s1'>{score} points can be used to offset ${score}</span>
                <Switch checked={checked} className='s3' onClick={(checked) => { this.setState({ checked }) }} />
              </div>
            </div> 
            :
            null
              
          }
          </MeScrollContainer>

          <div className='bottom bordertop'>
            <div className='cart-left'>
              <span className='all-money'>Real payment: ${sum.money}</span>
            </div>
            <div className='cart-rigth'>
              <div className="del-btn" onClick={this.submit.bind(this)}> place order </div>
            </div>
          </div>
        </div>



      
    )
  }

  

}


function mapStateToProps(state){
  let addressList = state.addressList.toJS()
  let address =addressList.find(item => item.checked )
  if( !address)
    address =addressList.find(item => item.is_default ==1 ) || addressList[0] ||{}
  console.log(state.tempCart.toJS())
  return {
    tempCart:state.tempCart.toJS(),
    address: address
  }
}
function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Actions, dispatch)
  }
}
export default  connect(
  mapStateToProps,
  mapDispatchToProps
)(ConfirmationOrder)
